import { View, ScrollView, Text } from '@tarojs/components'
import { useState, useEffect, useCallback, useMemo } from 'react'
import Taro from '@tarojs/taro'
import Header from '../../components/layout/Header'
import Banner from '../../components/layout/Banner'
import MainNav from '../../components/layout/MainNav'
import ProductList from '../../components/business/ProductList'
import HospitalList from '../../components/business/HospitalList'
import DoctorList from '../../components/business/DoctorList'
import {
  useBannersData, 
  useProductsData,
  useHospitalsData, 
  useDoctorsData,
  useProductFilterTags,
  useHospitalFilterTags,
  useDoctorFilterTags,
  useSearch,
  useHotSearch
} from '../../hooks/useData'
import {
  useDebounce
} from '../../hooks/usePerformance'
import { ProductSkeleton } from '../../components/common/Skeleton'
import EmptyState from '../../components/common/EmptyState'
import { usePreloadStrategy } from '../../hooks/usePreload'
import { useRouteCodeSplitting } from '../../hooks/useCodeSplitting'
import { usePersistentCache, usePersistentSearchHistory } from '../../hooks/usePersistentCache'
import './index.scss'

const Index = () => {
  // 当前激活的标签页
  const [activeTab, setActiveTab] = useState('钜惠商品')
  
  // 搜索状态
  const [isSearching, setIsSearching] = useState(false)
  const [searchKeyword, setSearchKeyword] = useState('')
  
  // 防抖搜索关键词
  const debouncedSearchKeyword = useDebounce(searchKeyword, 300)
  
  // 获取数据
  const bannersData = useBannersData()
  const { allProducts, getProductsByTag, getAllTags, loading: productsLoading } = useProductsData()
  const { hospitalsData, loading: hospitalsLoading } = useHospitalsData()
  const { allDoctors, getDoctorsByCategory, getAllCategories, loading: doctorsLoading } = useDoctorsData()
  
  // 获取搜索功能
  const { searchResults = {}, performSearch, clearSearch } = useSearch()
  const hotSearchWords = useHotSearch()
  
  // 获取筛选标签
  const { filterTags: productFilterTags } = useProductFilterTags(getAllTags)
  const { filterTags: hospitalFilterTags } = useHospitalFilterTags()
  const { filterTags: doctorFilterTags } = useDoctorFilterTags(getAllCategories)
  
  // 预加载策略
  const { preloadCurrentTab, preloadAdjacentTabs, preloadDetailRelated } = usePreloadStrategy()
  
  // 代码分割
  const { preloadRoute, preloadRelatedRoutes } = useRouteCodeSplitting()
  
  // 持久化缓存
  const { addHistory: addPersistentHistory } = usePersistentSearchHistory()
  
  // 当前激活的筛选标签
  const [activeProductFilter, setActiveProductFilter] = useState('推荐')
  const [activeHospitalFilter, setActiveHospitalFilter] = useState('推荐')
  const [activeDoctorFilter, setActiveDoctorFilter] = useState('推荐')

  // 检查数据是否已加载
  const isDataLoaded = bannersData && allProducts && hospitalsData && allDoctors
  const isLoading = productsLoading || hospitalsLoading || doctorsLoading || !isDataLoaded

  // 确保医院数据加载后，如果当前筛选器没有数据，自动切换到推荐
  useEffect(() => {
    if (hospitalsData && Object.keys(hospitalsData).length > 0) {
      const currentData = hospitalsData[activeHospitalFilter]
      if (!currentData || currentData.length === 0) {
        console.log('当前医院分类无数据，自动切换到推荐:', activeHospitalFilter)
        setActiveHospitalFilter('推荐')
      }
    }
  }, [hospitalsData, activeHospitalFilter])

  // 回到顶部功能
  const scrollToTop = useCallback(() => {
    // 使用Taro的页面滚动API
    Taro.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  }, [])
  
  // 处理搜索
  const handleSearch = async (keyword) => {
    if (!keyword.trim()) {
      clearSearch()
      setIsSearching(false)
      return
    }
    
    setIsSearching(true)
    try {
      // 传递当前标签页信息给搜索函数
      await performSearch(keyword, 'all', 1, 10, activeTab)
      // 添加到搜索历史
      addPersistentHistory(keyword)
    } catch (error) {
      console.error('搜索失败:', error)
    }
  }

  // 监听搜索关键词变化
  useEffect(() => {
    if (debouncedSearchKeyword) {
      handleSearch(debouncedSearchKeyword)
    } else {
      setIsSearching(false)
      clearSearch()
    }
  }, [debouncedSearchKeyword])

  // 自动切换到有数据的分类
  useEffect(() => {
    if (allProducts && allProducts.length > 0) {
      // 获取所有可用的标签
      const availableTags = getAllTags ? getAllTags() : ['推荐']
      // 只有在当前标签没有数据且不是"推荐"时才自动切换
      if (availableTags.length > 0 && 
          !availableTags.includes(activeProductFilter) && 
          activeProductFilter !== '推荐') {
        console.log('自动切换到有数据的商品标签:', availableTags[0])
        setActiveProductFilter(availableTags[0])
      }
    }
  }, [allProducts, activeProductFilter, getAllTags])

  useEffect(() => {
    if (hospitalsData && Object.keys(hospitalsData).length > 0) {
      const availableCategories = Object.keys(hospitalsData).filter(category => 
        hospitalsData[category] && hospitalsData[category].length > 0
      )
      // 只有在当前分类没有数据且不是"热门"时才自动切换
      if (availableCategories.length > 0 && 
          !availableCategories.includes(activeHospitalFilter) && 
          activeHospitalFilter !== '热门') {
        console.log('自动切换到有数据的医院分类:', availableCategories[0])
        setActiveHospitalFilter(availableCategories[0])
      }
    }
  }, [hospitalsData, activeHospitalFilter])

  useEffect(() => {
    if (allDoctors && allDoctors.length > 0) {
      // 获取所有可用的分类
      const availableCategories = getAllCategories ? getAllCategories() : ['推荐']
      // 只有在当前分类没有数据且不是"推荐"时才自动切换
      if (availableCategories.length > 0 && 
          !availableCategories.includes(activeDoctorFilter) && 
          activeDoctorFilter !== '推荐') {
        console.log('自动切换到有数据的医生分类:', availableCategories[0])
        setActiveDoctorFilter(availableCategories[0])
      }
    }
  }, [allDoctors, activeDoctorFilter, getAllCategories])

  // 处理标签页切换
  const handleTabChange = (tab) => {
    if (process.env.NODE_ENV === 'development') {
      console.log('切换到标签页:', tab)
    }
    
    // 立即切换标签页，不等待其他操作
    setActiveTab(tab)
    
    // 异步处理其他逻辑，不阻塞UI切换
    setTimeout(() => {
      // 重置筛选标签为"推荐"，确保每次切换都默认进入推荐
      setActiveProductFilter('推荐')
      setActiveHospitalFilter('推荐')
      setActiveDoctorFilter('推荐')
      
      // 预加载当前标签页数据
      preloadCurrentTab(tab)
      // 预加载相邻标签页数据
      preloadAdjacentTabs(tab)
    }, 0)
  }

  // 处理筛选标签切换
  const handleProductFilterChange = (filter) => {
    if (process.env.NODE_ENV === 'development') {
      console.log('切换到商品标签:', filter)
    }
    setActiveProductFilter(filter)
  }

  const handleHospitalFilterChange = (filter) => {
    if (process.env.NODE_ENV === 'development') {
      console.log('切换到医院分类:', filter)
      console.log('当前医院数据:', hospitalsData)
      console.log('目标分类数据:', hospitalsData[filter])
    }
    setActiveHospitalFilter(filter)
  }

  const handleDoctorFilterChange = (filter) => {
    if (process.env.NODE_ENV === 'development') {
      console.log('切换到医生分类:', filter)
    }
    setActiveDoctorFilter(filter)
  }

  // 处理商品点击
  const handleProductClick = (product) => {
    if (process.env.NODE_ENV === 'development') {
      console.log('点击商品:', product)
    }
    // 预加载详情页相关数据
    preloadDetailRelated('products', product._id || product.id)
    // 预加载相关路由
    preloadRelatedRoutes('product-detail')
    // 跳转到商品详情页
    Taro.navigateTo({
      url: `/packageB/pages/product-detail/product-detail?id=${product._id || product.id}`
    })
  }

  // 处理医院点击
  const handleHospitalClick = (hospital) => {
    if (process.env.NODE_ENV === 'development') {
      console.log('点击医院:', hospital)
    }
    // 预加载详情页相关数据
    preloadDetailRelated('hospitals', hospital._id || hospital.id)
    // 预加载相关路由
    preloadRelatedRoutes('hospital-detail')
    // 跳转到医院详情页
    Taro.navigateTo({
      url: `/packageB/pages/hospital-detail/hospital-detail?id=${hospital._id || hospital.id}`
    })
  }

  // 处理医生点击
  const handleDoctorClick = (doctor) => {
    if (process.env.NODE_ENV === 'development') {
      console.log('点击医生:', doctor)
    }
    // 这里可以添加跳转到医生详情页的逻辑
  }

  // 处理咨询功能
  const goToConsultation = () => {
    Taro.navigateTo({
      url: '/pages/chat/chat'
    })
  }

  // 渲染内容区域
  const renderContent = () => {
    if (isSearching) {
      // 根据当前标签页获取相应的搜索结果
      let currentResults = []
      if (activeTab === '钜惠商品') {
        currentResults = searchResults.products || []
      } else if (activeTab === '甄选机构') {
        currentResults = searchResults.hospitals || []
      } else if (activeTab === '口碑医生') {
        currentResults = searchResults.doctors || []
      } else {
        // 如果使用 filteredResults
        currentResults = searchResults.filteredResults || []
      }

      // 如果没有搜索结果，显示空状态
      if (!currentResults || currentResults.length === 0) {
        return (
          <EmptyState 
            type='search'
            title='未找到相关结果'
            description='请尝试其他关键词'
            actionText='重新搜索'
            onAction={() => setSearchKeyword('')}
          />
        )
      }

      // 根据当前标签页渲染相应的卡片组件
      switch (activeTab) {
        case '钜惠商品':
          return (
            <ProductList
              allProducts={currentResults}
              getProductsByTag={() => currentResults}
              productFilterTags={productFilterTags}
              activeFilter={activeProductFilter}
              onFilterChange={handleProductFilterChange}
              onProductClick={handleProductClick}
            />
          )
        case '甄选机构':
          // 将搜索结果转换为医院数据格式
          const hospitalData = { '搜索结果': currentResults }
          return (
            <HospitalList
              hospitalsData={hospitalData}
              hospitalFilterTags={hospitalFilterTags}
              activeFilter="搜索结果"
              onFilterChange={handleHospitalFilterChange}
              onHospitalClick={handleHospitalClick}
            />
          )
        case '口碑医生':
          return (
            <DoctorList
              allDoctors={currentResults}
              getDoctorsByCategory={() => currentResults}
              doctorFilterTags={doctorFilterTags}
              activeFilter={activeDoctorFilter}
              onFilterChange={handleDoctorFilterChange}
              onDoctorClick={handleDoctorClick}
            />
          )
        default:
          return (
            <EmptyState 
              type='search'
              title='未找到相关结果'
              description='请尝试其他关键词'
              actionText='重新搜索'
              onAction={() => setSearchKeyword('')}
            />
          )
      }
    }

    switch (activeTab) {
      case '钜惠商品':
        return (
          <ProductList
            allProducts={allProducts}
            getProductsByTag={getProductsByTag}
            productFilterTags={productFilterTags}
            activeFilter={activeProductFilter}
            onFilterChange={handleProductFilterChange}
            onProductClick={handleProductClick}
          />
        )
      case '甄选机构':
        return (
          <HospitalList
            hospitalsData={hospitalsData}
            hospitalFilterTags={hospitalFilterTags}
            activeFilter={activeHospitalFilter}
            onFilterChange={handleHospitalFilterChange}
            onHospitalClick={handleHospitalClick}
          />
        )
      case '口碑医生':
        return (
          <DoctorList
            allDoctors={allDoctors}
            getDoctorsByCategory={getDoctorsByCategory}
            doctorFilterTags={doctorFilterTags}
            activeFilter={activeDoctorFilter}
            onFilterChange={handleDoctorFilterChange}
            onDoctorClick={handleDoctorClick}
          />
        )
      default:
        return (
          <EmptyState 
            type='error' 
            title='页面错误' 
            actionText='返回首页'
            onAction={() => setActiveTab('钜惠商品')}
          />
        )
    }
  }

  return (
    <View className='index-page'>
      {isLoading ? (
        <View className='skeleton-page'>
          {/* 头部骨架屏 */}
          <View className='skeleton-header'>
            <View className='skeleton-header-content' />
          </View>
          
          {/* 轮播图骨架屏 */}
          <View className='skeleton-banner'>
            <View className='skeleton-banner-item' />
          </View>
          
          {/* 主导航骨架屏 */}
          <View className='skeleton-nav'>
            {[1, 2, 3].map((i) => (
              <View key={i} className='skeleton-nav-item' />
            ))}
          </View>
          
          {/* 筛选标签骨架屏 */}
          <View className='skeleton-filter-tags'>
            {[1, 2, 3, 4, 5].map((i) => (
              <View key={i} className='skeleton-filter-tag' />
            ))}
          </View>
          
          {/* 商品列表骨架屏 */}
          <View className='skeleton-product-grid'>
            {[1, 2, 3, 4, 5, 6].map((i) => (
              <View key={i} className='skeleton-product-card'>
                <View className='skeleton-product-image' />
                <View className='skeleton-product-info'>
                  <View className='skeleton-product-title' />
                  <View className='skeleton-product-title-short' />
                  <View className='skeleton-product-price' />
                  <View className='skeleton-product-footer' />
                </View>
              </View>
            ))}
          </View>
        </View>
      ) : (
        <>
          {/* 头部 */}
          <View className='fade-in-up'>
            <Header 
              onSearch={setSearchKeyword}
              onConsultation={goToConsultation}
              onMagicMirror={() => {
                console.log('跳转到新氧魔镜页面')
                Taro.navigateTo({
                  url: '/pages/ai/Main/Main'
                }).catch(() => {
                  Taro.showToast({
                    title: '无法打开魔镜页面',
                    icon: 'none'
                  })
                })
              }}
              onAIQuery={() => {
                console.log('跳转到AI查询页面')
                Taro.navigateTo({
                  url: '/pages/ai/Main/Main'
                }).catch(() => {
                  Taro.showToast({
                    title: '无法打开AI查询页面',
                    icon: 'none'
                  })
                })
              }}
            />
          </View>
          
          {/* 轮播图 */}
          <View className='slide-in-left'>
            <Banner banners={bannersData} />
          </View>
          
          {/* 主导航 */}
          <View className='slide-in-right'>
            <MainNav 
              activeTab={activeTab}
              onTabChange={handleTabChange}
            />
          </View>
          
          {/* 内容区域 */}
          <View className='content-area scale-in'>
            {renderContent()}
          </View>
        </>
      )}
    </View>
  )
}

export default Index